package middleware

import (
	"fmt"
	"gitee.com/fatzeng/srf_switch_basic_components/switch_log"
	"gitee.com/fatzeng/srf_switch_dynamic_logic_director/component"
	"gitee.com/fatzeng/srf_switch_dynamic_logic_director/dao"
	"github.com/gin-gonic/gin"
)

const USER_INFO = "userInfo"

func IdentityVerification() gin.HandlerFunc {
	return func(c *gin.Context) {
		token := c.GetHeader("Authorization")
		if token == "" {
			switch_log.Logger().Error("IdentityVerification has error: ", "token is empty")
			c.Abort()
			return
		}
		userid, err := component.ParseJwt(token)
		if err != nil {
			switch_log.Logger().Error("IdentityVerification has error: ", "token format error")
			c.Abort()
			return
		}
		err, info := dao.GetUserInfoByUserId(userid)
		if err != nil {
			switch_log.Logger().Error("IdentityVerification has error: ", fmt.Sprintf("Unable to find corresponding user based on: %v error is : %v", userid, err))
			c.Abort()
			return
		}
		if info == nil {
			switch_log.Logger().Error("IdentityVerification has error: ", fmt.Sprintf("Unable to find corresponding user based on: %v", userid))
			c.Abort()
			return
		}

		if info.IsDeleted == 1 {
			switch_log.Logger().Error("IdentityVerification has error: ", fmt.Sprintf("The user has been deleted: %v", userid))
			c.Abort()
			return
		}
		if info.IsActive == 2 {
			switch_log.Logger().Error("IdentityVerification has error: ", fmt.Sprintf("User not activated: %v", userid))
			c.Abort()
			return
		}

		c.Set(USER_INFO, info)
		c.Next()
	}

}
